package com.hangsu.train.components.web.utils;


import com.hangsu.train.components.entity.Permiss;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lyy
 * @Date 2021/12/7
 */
public class PermissUtils {

    public static List<Permiss> transToTree(List<Permiss> sources) {
        if (sources == null || sources.isEmpty()) {
            return Collections.emptyList();
        }

        Map<Long, Permiss> sourceMap = sources.stream().collect(Collectors.toMap(Permiss::getId, e -> e));
        Map<Long, List<Permiss>> pIdToChildrenListMap = sources.stream().collect(Collectors.groupingBy(Permiss::getParentId));

        List<Long> willBeRemovedIdList = new LinkedList<>();
        for (Map.Entry<Long, List<Permiss>> entry : pIdToChildrenListMap.entrySet()) {
            Permiss permiss = sourceMap.get(entry.getKey());
            if (permiss != null) {
                permiss.setChildren(entry.getValue().stream().sorted(Comparator.comparing(Permiss::getSort)).collect(Collectors.toList()));
                willBeRemovedIdList.add(entry.getKey());
            }
        }
        willBeRemovedIdList.forEach(pIdToChildrenListMap::remove);
        return pIdToChildrenListMap.values().stream().flatMap(Collection::stream).sorted(Comparator.comparing(Permiss::getSort)).collect(Collectors.toList());
    }
}
